package com.py.credit.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.service.CreditReportService;
import com.py.credit.service.SSearchService;
import com.py.credit.service.ScontentService;
import com.py.credit.service.WebBgdzService;
import com.py.credit.service.WebCreditReportService;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.FreeeMarkerUtils;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.helper.UrlHelper;
import com.py.framework.core.http.HttpAgent;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 门户网站申请核查报告controller
 */
@RestController
@RequestMapping(value = "/creditreport")
public class CreditReportController {

    private static Logger logger = Logger.getLogger(CreditReportController.class);

    @Autowired
    private WebCreditReportService webcreditreportService;

    @Value("${absolutepath}")
    private String absolutepath;

    @Value("${pdfJsPath}")
    private String pdfJsPath;

    @Value("${googlePath}")
    private String googlePath;

    @Value("${pdfPagePathWeb}")
    private String pdfPagePathWeb;
    @Autowired
    private CreditReportService creditReportService;

    @Autowired
    private ScontentService sContentService;

    @Autowired
    private SSearchService sSearchService;

    @Autowired
    private WebBgdzService webBgdzService;

    @Autowired
    private UrlHelper urlHelper;

    @IgnoreAuthority
    @RequestMapping(value = "/addcreditreport.json")

    public Object addCheck(@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                           HttpServletRequest request) {
        Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
        RestServiceResult<String> result = new RestServiceResult<String>();
        try {
            String ztmc = parseObject.get("ztmc");
            String tybm = "";
            String A000002 = parseObject.get("A000002");
            String gszch = parseObject.get("gszch");
            String fddbrmc = parseObject.get("fddbrmc");
            String fddbrzjhm = parseObject.get("fddbrzjhm");
            String jbrxm = parseObject.get("jbrxm");
            String jbrzjhm = parseObject.get("jbrzjhm");
            String jbrlxdh = parseObject.get("jbrlxdh");
            String cxyt = parseObject.get("cxyt");
            String type = parseObject.get("type");

            //根据type对申领用户信息校验

            Map<String, String> frdata = webcreditreportService.checkFr(ztmc, A000002, gszch);
            if (frdata != null && !frdata.isEmpty()) {
                if (frdata.get("FDDBR") != null && !frdata.get("FDDBR").equals("null")) {
                    if (frdata.get("FDDBRZJHM") != null && !frdata.get("FDDBRZJHM").equals("null")) {
                        if (!frdata.get("FDDBR").equals(fddbrmc) || !frdata.get("FDDBRZJHM").equals(fddbrzjhm)) {

                            result.setMsg("法定代表人和身份证号不匹配");
                        } else {
                            tybm = frdata.get("tybm");

                            result.setMsg("校验通过");
                            //生成信用报告
                            Map<String, Object> templateData = this.getTemplateData(tybm, "100000", ztmc, null);
                            String filePath = absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm;
//                            boolean googleConvent = Html2Pdf.builderPdf(templateData, "/template/pdf_web_template_freemarker.ftl", filePath, ztmc + ".pdf");
                            boolean googleConvent = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_web_template_freemarker.ftl", filePath, ztmc + ".pdf", absolutepath);

//    					        boolean googleConvent = HtmlToPdfUtils.googleConvent(pdfJsPath,
//    					        		pdfPagePathWeb + "/tybm=" + tybm + "/kId=" + 100000 + "/keyword=" + ztmc,
//    					                absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm, ztmc+".pdf", null, true,
//    					                googlePath);
                            String path = "";
                            if (googleConvent) {
                                path = ResourcePath.CREDIT_REPORT_DIR + tybm + File.separator + ztmc + ".pdf";
                            }
                            String sqbh = UuidUtil.getInstance().getUUid();
                            //将数据记录
                            webcreditreportService.addcreditreport(ztmc, A000002, gszch, fddbrmc, fddbrzjhm, jbrxm, jbrzjhm, jbrlxdh, cxyt, type, path, sqbh);
                            result.setData(sqbh);
                            result.setMsg("提交成功");
                        }
                    } else {
                        tybm = frdata.get("tybm");

                        result.setMsg("校验通过");


                        //生成信用报告
                        Map<String, Object> templateData = this.getTemplateData(tybm, "100000", ztmc, null);
                        String filePath = absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm;
//                        boolean googleConvent = Html2Pdf.builderPdf(templateData, "/template/pdf_web_template_freemarker.ftl", filePath, ztmc + ".pdf");
                        boolean googleConvent = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_web_template_freemarker.ftl", filePath, ztmc + ".pdf", absolutepath);

//					        boolean googleConvent = HtmlToPdfUtils.googleConvent(pdfJsPath,
//					        		pdfPagePathWeb + "/tybm=" + tybm + "/kId=" + 100000 + "/keyword=" + ztmc,
//					                absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm, ztmc+".pdf", null, true,
//					                googlePath);
                        String path = "";
                        if (googleConvent) {
                            path = ResourcePath.CREDIT_REPORT_DIR + tybm + File.separator + ztmc + ".pdf";
                        }
                        String sqbh = UuidUtil.getInstance().getUUid();
                        //将数据记录
                        webcreditreportService.addcreditreport(ztmc, A000002, gszch, fddbrmc, fddbrzjhm, jbrxm, jbrzjhm, jbrlxdh, cxyt, type, path, sqbh);
                        result.setData(sqbh);
                        result.setMsg("提交成功");
                    }
                } else {

                    result.setMsg("法定代表人和身份证号不匹配");
                }
            } else {
                result.setMsg("该法人数据尚未录入，请核查");
            }
            return result;


        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("提交报告申领异常");
            ExceptionLogger.error("提交报告申领异常！", e.getMessage(), e);
        }
        return result;
    }


    @IgnoreAuthority
    @RequestMapping(value = "/reportExportYz.json")
    public RestServiceResult<List<Map<String, Object>>> addCheck(
            @RequestParam(value = "qymc", defaultValue = "", required = true) String qymc,
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            String pch, String pcId, String id, HttpServletRequest request) {

        String jdToken = HttpServletHelper.getUserToken(request);

        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        try {
            //生成信用报告
            Map<String, Object> templateData = this.getTemplateData(tybm, "100000", qymc, pcId);
            String filePath = absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch;
            boolean googleConvent = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_web_template_freemarker.ftl", filePath, qymc + ".pdf", absolutepath);

            if (googleConvent) {
                updateReportStatus(id, pch, "1", jdToken);
                r.setData(rep);
                return r;
            } else {
                updateReportStatus(id, pch, "2", jdToken);
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("生成报告失败");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            }
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("生成报告失败！", e.getMessage(), e);
        }
        return r;
    }

    private void updateReportStatus(String id, String pch, String flag, String jdToken) {
        String url = urlHelper.getBaseXypjUrl() + "/reportGet/updateReportStatus.do";
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", id);
        params.put("pch", pch);
        params.put("flag", flag);
        String result = "";
        try {
            // 发送请求
            result = HttpAgent.getInstance().sendHttpPost(url, params, null);
            logger.info("[CreditReportController.updateReportStatus] result:" + result);
            System.out.println("[CreditReportController.updateReportStatus] result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            RestServiceResult<List<Object>> userData = new RestServiceResult<>();
            userData.setCode(RestServiceResult.CODE_UNKNOW);
            userData.setMsg("系统异常，请稍后再试！");
            ExceptionLogger.error(
                    "远程服务-获取当前用户信息调用异常！(XypjRemoteBaseService#getRolesByUserId) URL:" + url + "Result:" + result,
                    e.getMessage(), e);
        }
    }

    /**
     * 信用报告申领审核
     *
     * @param condition
     * @param request
     * @return
     */
    @IgnoreAuthority
    @RequestMapping(value = "/checkInfo.json")

    public Object checkInfo(@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                            HttpServletRequest request) {
        Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
        RestServiceResult<String> result = new RestServiceResult<String>();
        try {
            String ztmc = parseObject.get("ztmc");
            String A000002 = parseObject.get("A000002");
            String gszch = parseObject.get("gszch");
            String fddbrmc = parseObject.get("fddbrmc");
            String fddbrzjhm = parseObject.get("fddbrzjhm");
            String jbrxm = parseObject.get("jbrxm");
            String jbrzjhm = parseObject.get("jbrzjhm");
            String jbrlxdh = parseObject.get("jbrlxdh");
            String cxyt = parseObject.get("cxyt");
            String type = parseObject.get("type");
            Map<String, String> checkdata = new HashMap<String, String>();
            //根据type对申领用户信息校验
            if (type.equals("100000")) {
                Map<String, String> frdata = webcreditreportService.checkFr(ztmc, A000002, gszch);
                if (!frdata.isEmpty()) {
                    if (!frdata.get("FDDBR").equals(fddbrmc) || !frdata.get("FDDBRZJHM").equals(fddbrzjhm)) {

                        result.setMsg("法定代表人和身份证号不匹配");
                    } else {
                        result.setData(frdata.get("tybm"));
                        result.setMsg("校验通过");
                    }
                } else {
                    result.setMsg("该法人数据尚未录入，请核查");
                }
                return result;
            } else {
                checkdata = webcreditreportService.checkZrr(fddbrmc, fddbrzjhm);
                if (checkdata.get("tybm") != null && !checkdata.get("tybm").equals("")) {
                    result.setData(checkdata.get("tybm"));
                    result.setMsg("校验通过");
                } else {
                    result.setMsg("请输入正确的姓名和身份证号");
                }
                return result;
            }

        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("核查报告申领校验异常");
            ExceptionLogger.error("核查报告申领校验异常！", e.getMessage(), e);
            return result;
        }

    }

    @IgnoreAuthority
    @RequestMapping(value = "/getReportData.json")
    public RestServiceResult<Map<String, Object>> getReportData(@RequestParam(value = "tybm") String tybm,
                                                                @RequestParam(value = "kId") String kId) {
        RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();

        Map<String, Object> reportData = webcreditreportService.getReportData(tybm, kId);
        result.setData(reportData);
        return result;

    }

    /**
     * 查询信用报告申领历史
     *
     * @param condition
     * @param lqzt
     * @param ztmc
     * @param type
     * @return
     */
    @IgnoreAuthority
    @RequestMapping(value = "/creditreportHistory.json")
    public RestServiceResult<List<Map<String, String>>> creditreportHistory(
            @RequestParam(value = "lqzt", required = false, defaultValue = "") String lqzt, @RequestParam(value = "ztmc", required = false, defaultValue = "") String ztmc, @RequestParam(value = "type", required = false, defaultValue = "") String type, Page page) {
        RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<List<Map<String, String>>>();
        List<Map<String, String>> reportData = webcreditreportService.getcreditreportHistoryForPage(ztmc, lqzt, type, page);
        result.setData(reportData);
        return result;

    }

    /**
     * 门户查询信用报告申领历史
     *
     * @param condition
     * @param lqzt
     * @param ztmc
     * @param type
     * @return
     */
    @IgnoreAuthority
    @RequestMapping(value = "/WebcreditreportHistory.json")
    public RestServiceResult<List<Map<String, String>>> WebcreditreportHistory(@RequestParam(value = "condition", required = false, defaultValue = "") String condition) {
        RestServiceResult<List<Map<String, String>>> result = new RestServiceResult<List<Map<String, String>>>();
        Page page = new Page();
        try {
            Map<String, Object> map = JSON.parseObject(condition);
            page.setLimit(Integer.parseInt(String.valueOf(map.get("limit"))));

            page.setPage(Integer.parseInt(String.valueOf(map.get("page"))) / Integer.parseInt(String.valueOf(map.get("limit"))) + 1);

            result.setData(webcreditreportService.getcreditreportHistoryForPage(null, null, null, page));
            result.setCount(page.getTotalCount());


        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("查询信用报告申领历史失败");
        }
        return result;
    }

    /**
     * 门户网址下载信用报告，并将报告状态改为已领取
     *
     * @param id
     * @param response
     * @param request
     */
    @IgnoreAuthority
    @RequestMapping(value = "/updatecreditreportStatus.json")

    public Object updatecreditreportStatus(@RequestParam(value = "condition", required = true, defaultValue = "") String condition,
                                           HttpServletResponse response, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        Map<String, String> parseObject = JSONObject.parseObject(condition, Map.class);
        try {
            String path = absolutepath + webcreditreportService.creditreportPreview(parseObject.get("sqbh"));
            result.setData(path);
            if (!new File(path).exists()) {
                throw new ServiceException("文件不存在，或者已经被移除！");
            }
            webcreditreportService.updatecreditreportStatus(parseObject.get("sqbh"));
            return result;
        } catch (Exception e) {
            result.setMsg("文件下载失败");
            return result;
        }
    }

    @IgnoreAuthority
    @RequestMapping(value = "/downloadPdf.json")
    public Object downloadPdf(@RequestParam(value = "sqbh", required = true, defaultValue = "") String sqbh,
                              HttpServletResponse response, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();

        try {
            String path = absolutepath + webcreditreportService.creditreportPreview(sqbh);
            FileUtil.downloadFile(path, response);

            webcreditreportService.updatecreditreportStatus(sqbh);
            return result;
        } catch (Exception e) {
            result.setMsg("文件下载失败");
            return result;
        }
    }

    private Map<String, Object> getTemplateData(String tybm, String kId, String qymc, String pcId) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> detail = this.sContentService.getDetail("100000", tybm, "JKSQ", null);
        this.sSearchService.addHistory(tybm, "100000", -1L);
        Map<String, Object> data = this.sSearchService.xyhcassembleTableComponentForMHWZ((List) detail.get("results"), qymc, tybm);
        List<Map> jbxxList = (List<Map>) data.get("基本信息");
        List<Map> gsdjxxList = (List<Map>) ((Map) jbxxList.get(0)).get("工商登记信息");
        if (null != jbxxList && jbxxList.size() > 0 && null != gsdjxxList && gsdjxxList.size() > 0) {
            Map gsdjxx = gsdjxxList.get(0);
            result.put("A000001", isNull(gsdjxx.get("A000001")));
            result.put("A000002", isNull(gsdjxx.get("A000002")));
            result.put("dz", isNull(gsdjxx.get("DZ")));
            result.put("fddbr", isNull(gsdjxx.get("FDDBR")));
            result.put("qylx", isNull(gsdjxx.get("qylx")));
            result.put("clrq", formatDate(gsdjxx.get("CLRQ")));
            result.put("jyfw", isNull(gsdjxx.get("JYFW")));
        } else {
            result.put("A000001", "-");
            result.put("A000002", "-");
            result.put("dz", "-");
            result.put("fddbr", "-");
            result.put("qylx", "-");
            result.put("clrq", "-");
            result.put("jyfw", "-");
        }
        List<Map> xzxkList = (List<Map>) data.get("行政许可");
        if (null != xzxkList && xzxkList.size() > 0) {
            Map frxzxkMap = xzxkList.get(0);
            int xzxkDataCount = 0;
            if (null != frxzxkMap && Integer.valueOf(String.valueOf(frxzxkMap.get("size"))).intValue() > 0) {
                List<Map> frxzxk = (List<Map>) frxzxkMap.get("法人行政许可");
                xzxkDataCount = Integer.valueOf(String.valueOf(frxzxkMap.get("size"))).intValue();
                StringBuilder xzxkDataDom = new StringBuilder();
                for (int i = 0; i < frxzxk.size(); i++) {
                    xzxkDataDom.append("<table><tr><th style=\"width:30%\"></th><th>第").append(i + 1).append("条</th></tr>");
                    xzxkDataDom.append("<tr><td style=\"width:30%\">行政许可决定文书号：</td><td style=\"width:70%\">").append(isNull(frxzxk.get(i).get("XK_WSH"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>行政许可决定文书名称：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKWS"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可证书名称：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKZS"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可类别：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKLB"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可编号：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKBH"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可决定日期：</td><td>").append(formatDate(frxzxk.get(i).get("XK_JDRQ"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>有效期自：</td><td>").append(formatDate(frxzxk.get(i).get("XK_YXQZ"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>有效期至：</td><td>").append(formatDate(frxzxk.get(i).get("XK_YXQZI"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可内容：</td><td>").append(isNull(frxzxk.get(i).get("XK_NR"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可机关：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKJG"))).append("</td></tr>");
                    xzxkDataDom.append("<tr><td>许可机关统一社会信用代码：</td><td>").append(isNull(frxzxk.get(i).get("XK_XKJGDM"))).append("</td></tr>");
                    xzxkDataDom.append("</table>");
                }
                result.put("xzxkDataDom", xzxkDataDom.toString());
            } else {
                result.put("xzxkDataDom", "");
            }
            if (xzxkDataCount == 0)
                result.put("xzxkDataStyle", Integer.valueOf(xzxkDataCount));
            if (xzxkDataCount == 0) {
                result.put("xzxkDataStyle", "style=\"display: none;\"");
            } else {
                result.put("xzxkDataStyle", "style=\"display: block;\"");
            }
            result.put("xzxkDataCount", Integer.valueOf(xzxkDataCount));
            result.put("ggxx_xzxk", xzxkDataCount + "条");
        }

        List<Map> xzcfList = (List<Map>) data.get("行政处罚");
        if (null != xzcfList && xzcfList.size() > 0) {
            Map frxzcfMap = xzcfList.get(0);
            int xzcfDataCount = 0;
            if (null != frxzcfMap && Integer.valueOf(String.valueOf(frxzcfMap.get("size"))).intValue() > 0) {
                List<Map> frxzcf = (List<Map>) frxzcfMap.get("法人行政处罚");
                xzcfDataCount = Integer.valueOf(String.valueOf(frxzcfMap.get("size"))).intValue();
                StringBuilder xzcfDataDom = new StringBuilder();
                for (int i = 0; i < frxzcf.size(); i++) {
                    xzcfDataDom.append("<table><tr><th style=\"width:30%\"></th><th >第").append((i + 1)).append("条</th></tr>");
                    xzcfDataDom.append("<tr><td style=\"width:30%\">行政处罚决定文书号：</td><td style=\"width:70%\">").append(isNull(frxzcf.get(i).get("CF_WSH"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>违法行为类型：</td><td>").append(isNull(frxzcf.get(i).get("CF_WFXW"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚事由：</td><td>").append(isNull(frxzcf.get(i).get("CF_SY"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚类别：</td><td>").append(isNull(frxzcf.get(i).get("CF_LB"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚依据：</td><td>").append(isNull(frxzcf.get(i).get("CF_YJ"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚内容：</td><td>").append(isNull(frxzcf.get(i).get("CF_NR"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>罚款金额（万元）：</td><td>").append(isNull(frxzcf.get(i).get("CF_NR_FK"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>没收违法所得、没收非法财物的金额（万元）：</td><td>").append(isNull(frxzcf.get(i).get("CF_NR_WFFF"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>暂扣或吊销证照名称及编号：</td><td>").append(isNull(frxzcf.get(i).get("CF_NR_ZKDX"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚有效期：</td><td>").append(formatDate(frxzcf.get(i).get("CF_YXQ"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>公示截止期：</td><td>").append(formatDate(frxzcf.get(i).get("CF_GSJZQ"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚机关：</td><td>").append(isNull(frxzcf.get(i).get("CF_CFJG"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>处罚机关统一社会信用代码：</td><td>").append(isNull(frxzcf.get(i).get("CF_CFJGDM"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>数据来源单位：</td><td>").append(isNull(frxzcf.get(i).get("CF_SJLY"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>数据来源单位统一社会信用代码：</td><td>").append(isNull(frxzcf.get(i).get("CF_SJLYDM"))).append("</td></tr>");
                    xzcfDataDom.append("<tr><td>备注：</td><td>").append(isNull(frxzcf.get(i).get("BZ"))).append("</td></tr>");
                    xzcfDataDom.append("</table>");
                }
                result.put("xzcfDataDom", xzcfDataDom.toString());
            } else {
                result.put("xzcfDataDom", "");
            }
            if (xzcfDataCount == 0) {
                result.put("xzcfDataStyle", "style=\"display: none;\"");
            } else {
                result.put("xzcfDataStyle", "style=\"display: block;\"");
            }
            result.put("xzcfDataCount", Integer.valueOf(xzcfDataCount));
            result.put("ggxx_xzcf", xzcfDataCount + "条");
        }
        List<Map> sxjlList = (List<Map>) data.get("守信激励");
        if (null != sxjlList && sxjlList.size() > 0) {
            Map xsjlMap = sxjlList.get(0);
            int sxjlDataCount = 0;
            if (null != xsjlMap && Integer.valueOf(String.valueOf(xsjlMap.get("size"))).intValue() > 0) {
                List<Map> ajnsr = (List<Map>) xsjlMap.get("A级纳税人");
                sxjlDataCount = Integer.valueOf(String.valueOf(xsjlMap.get("size"))).intValue();
                StringBuilder sxjlDataDom = new StringBuilder();
                for (int i = 0; i < ajnsr.size(); i++) {
                    sxjlDataDom.append("<table><tr><th style=\"width:30%\"></th><th >第").append(i + 1).append("条</th></tr>");
                    sxjlDataDom.append("<tr><td style=\"width:30%\">认定单位：</td><td style=\"width:70%\">").append(isNull(ajnsr.get(i).get("pjswjg"))).append("</td></tr>");
                    sxjlDataDom.append("<tr><td>评价结果：</td><td>").append(isNull(ajnsr.get(i).get("pjjg"))).append("</td></tr>");
                    sxjlDataDom.append("<tr><td>评价年度：</td><td>").append(isNull(ajnsr.get(i).get("pjnd"))).append("</td></tr>");
                    sxjlDataDom.append("</table>");
                }
                result.put("sxjlDataDom", sxjlDataDom.toString());
            } else {
                result.put("sxjlDataDom", "");
            }
            if (sxjlDataCount == 0) {
                result.put("sxjlDataStyle", "style=\"display: none;\"");
            } else {
                result.put("sxjlDataStyle", "style=\"display: block;\"");
            }
            result.put("sxjlDataCount", Integer.valueOf(sxjlDataCount));
            result.put("ggxx_sxjl", sxjlDataCount + "条");
        }
        int sxcjDataCount = 0;
        StringBuilder sxcjDataDom1 = new StringBuilder();
        StringBuilder sxcjDataDom2 = new StringBuilder();
        List<Map> sxcjList = (List<Map>) data.get("失信惩戒");
        if (null != sxcjList && sxcjList.size() > 0)
            for (int i = 0; i < sxcjList.size(); i++) {
                Map map = sxcjList.get(i);
                if (null != map.get("size"))
                    sxcjDataCount += Integer.valueOf(String.valueOf(map.get("size"))).intValue();
                if (null != map.get("失信被执行人")) {
                    List<Map> sxzxrList = (List<Map>) map.get("失信被执行人");
                    for (int j = 0; j < sxzxrList.size(); j++) {
                        sxcjDataDom2.append("<table><tr><th style=\"width:30%\">失信被执行人</th><th>第").append((i + 1)).append("条</th></tr>");
                        sxcjDataDom2.append("<tr><td style=\"width:30%\">行政处罚决定书文号：</td><td style=\"width:70%\">").append(isNull(sxzxrList.get(j).get("CF_WSH"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>违法行为类型：</td><td>").append(isNull(sxzxrList.get(j).get("CF_WFXW"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>违法事实：</td><td>").append(isNull(sxzxrList.get(j).get("CF_SY"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚依据：</td><td>").append(isNull(sxzxrList.get(j).get("ah"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚类别：</td><td>").append(isNull(sxzxrList.get(j).get("CF_CFLB"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚内容：</td><td>").append(isNull(sxzxrList.get(j).get("CF_NR"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>罚款金额（万元）：</td><td>").append(isNull(sxzxrList.get(j).get("CF_NR_FK"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>没收违法所得、没收非法财物的金额（万元）：</td><td>").append(isNull(sxzxrList.get(j).get("CF_NR_WFFF"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>暂扣或吊销证照名称及编号：</td><td>").append(isNull(sxzxrList.get(j).get("CF_NR_ZKDX"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚决定日期：</td><td>").append(formatDate(sxzxrList.get(j).get("creditTime"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚有效期：</td><td>").append(isNull(sxzxrList.get(j).get("CF_YXQ"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>公示截止期：</td><td>").append(isNull(sxzxrList.get(j).get("CF_GSJZQ"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚机关：</td><td>").append(isNull(sxzxrList.get(j).get("zxfy"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>处罚机关统一社会信用代码：</td><td>").append(isNull(sxzxrList.get(j).get("CF_CFJGDM"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>数据来源单位：</td><td>").append(isNull(sxzxrList.get(j).get("A000001"))).append("</td></tr>");
                        sxcjDataDom2.append("<tr><td>数据来源单位统一社会信用代码：</td><td>").append(isNull(sxzxrList.get(j).get("A000002"))).append("</td></tr></table></div>");
                    }
                }
                if (null != map.get("重大税收违法案件")) {
                    List<Map> zdsswfList = (List<Map>) map.get("重大税收违法案件");
                    for (int j = 0; j < zdsswfList.size(); j++) {
                        sxcjDataDom1.append("<table><tr><th style=\"width:30%\">重大税收违法案件</th><th>第").append(i + 1).append("条</th></tr>");
                        sxcjDataDom1.append("<tr><td style=\"width:30%\">黑名单名称：</td><td style=\"width:70%\">").append(isNull(zdsswfList.get(j).get("A000001"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>列入名单事由：</td><td>").append(isNull(zdsswfList.get(j).get("zywfss"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>认定依据：</td><td>").append(isNull(zdsswfList.get(j).get("clcfqk"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>认定日期：</td><td>").append(formatDate(zdsswfList.get(j).get("larq"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>有效期始：</td><td>").append(isNull(zdsswfList.get(j).get("RDRQ"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>有效期至：</td><td>").append(isNull(zdsswfList.get(j).get("YXQZ"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>认定单位：</td><td>").append(isNull(zdsswfList.get(j).get("deptName"))).append("</td></tr>");
                        sxcjDataDom1.append("<tr><td>认定单位统一社会信用代码：</td><td>").append(isNull(zdsswfList.get(j).get("A000002"))).append("</td></tr></table></div>");

                    }
                }
            }
        result.put("sxcjDataCount", Integer.valueOf(sxcjDataCount));
        if (sxcjDataCount == 0) {
            result.put("sxcjDataStyle", "style=\"display: none;\"");
        } else {
            result.put("sxcjDataStyle", "style=\"display: block;\"");
        }
        result.put("ggxx_sxcj", sxcjDataCount + "条");
        result.put("sxcjDataDom", sxcjDataDom1.append(sxcjDataDom2).toString());


        List<Map> zdgzList = (List<Map>) data.get("重点关注");
        if (null != zdgzList && zdgzList.size() > 0) {
            Map zdgzMap = zdgzList.get(0);
            int zdgzDataCount = 0;
            if (null != zdgzMap && Integer.valueOf(String.valueOf(zdgzMap.get("size"))).intValue() > 0) {
                List<Map> jyycmlList = (List<Map>) zdgzMap.get("经营异常名录");
                zdgzDataCount = Integer.valueOf(String.valueOf(zdgzMap.get("size"))).intValue();
                StringBuilder zdgzDataDom = new StringBuilder();
                for (int i = 0; i < jyycmlList.size(); i++) {
                    zdgzDataDom.append("<table><tr><th style='width:30%'></th><th>第").append(i + 1).append("条</th></tr>");
                    zdgzDataDom.append("<tr><td style='width:30%'>企业名称：</td><td style='width:70%'>").append(isNull(jyycmlList.get(i).get("A000001"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>列入经营异常名录原因：</td><td>").append(isNull(jyycmlList.get(i).get("pjjgpjjg"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>列入日期：</td><td>").append(formatDate(jyycmlList.get(i).get("lrrq"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>做出决定机关(列入)：</td><td>").append(isNull(jyycmlList.get(i).get("lrjdjg"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>移出异常名录原因：</td><td>").append(isNull(jyycmlList.get(i).get("ycyy"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>移出日期：</td><td>").append(formatDate(jyycmlList.get(i).get("ycrq"))).append("</td></tr>");
                    zdgzDataDom.append("<tr><td>做出决定机关(移出)：</td><td>").append(isNull(jyycmlList.get(i).get("ycjdjg"))).append("</td></tr>");
                    zdgzDataDom.append("</table>");
                }
                result.put("zdgzDataDom", zdgzDataDom.toString());
            } else {
                result.put("zdgzDataDom", "");
            }
            if (zdgzDataCount == 0) {
                result.put("zdgzDataStyle", "style=\"display: none;\"");
            } else {
                result.put("zdgzDataStyle", "style=\"display: block;\"");
            }
            result.put("zdgzDataCount", Integer.valueOf(zdgzDataCount));
            result.put("ggxx_zdgz", zdgzDataCount + "条");
        }
        /*Hcbg latest = this.webBgdzService.getLatest();
        result.put("bgbh", latest.getReportNo() + DateUtils.getCurrentTimeNumber());
        result.put("addressBg", latest.getReportProducer());
        result.put("title", latest.getReportStatment());
        if (StringUtils.isNotBlank(latest.getWatermarker())) {
            result.put("waterPath", latest.getWatermarker().substring(0, latest.getWatermarker().lastIndexOf("/") + 1));
            result.put("watermark", latest.getWatermarker().substring(latest.getWatermarker().lastIndexOf("/") + 1));
        } else {
            result.put("watermark", "watermark.png");
        }*/
        String url = urlHelper.getBaseXypjUrl() + "/creditReportConfig/getReportDetail.json";
        try {
            // 发送请求
            String str = HttpAgent.getInstance().sendHttpPost(url, null);
            JSONObject json = JSONObject.parseObject(str);
            JSONObject jsonData = json.getJSONObject("data");
            result.put("bgbh", "XYBG" + DateUtils.getCurrentTimeNumber());
            result.put("addressBg", isBlank(jsonData.getString("dept")) ? "" : jsonData.getString("dept"));
            result.put("title", isBlank(jsonData.getString("reportStatement")) ? "" : jsonData.getString("reportStatement"));

            if (isBlank(jsonData.getString("REPORT_WATERMARK"))) {
                result.put("waterPath", "/images/watermark/");
                result.put("water", "watermark.png");
            } else {
                result.put("waterPath", jsonData.getString("REPORT_WATERMARK").substring(0, jsonData.getString("REPORT_WATERMARK").lastIndexOf("/") + 1));
                result.put("water", jsonData.getString("REPORT_WATERMARK").substring(jsonData.getString("REPORT_WATERMARK").lastIndexOf("/") + 1));
            }
            if (isBlank(jsonData.getString("ENTERPRISE_ICON"))) {
                result.put("iconPath", "icon.png");
            } else {
                result.put("iconPath", jsonData.getString("ENTERPRISE_ICON").substring(jsonData.getString("ENTERPRISE_ICON").lastIndexOf("/") + 1));
            }
        } catch (Exception e) {
            RestServiceResult<List<Object>> userData = new RestServiceResult<>();
            userData.setCode(RestServiceResult.CODE_UNKNOW);
            userData.setMsg("系统异常，请稍后再试！");
            ExceptionLogger.error(
                    "远程服务-获取当前用户信息调用异常！(XypjRemoteBaseService#getReportDetail) URL:" + url + "Result:" + result,
                    e.getMessage(), e);
        }
        String url2 = urlHelper.getBaseXypjUrl() + "/modelTest/getxydjInfo.json";
        if (StringUtils.isNotBlank(pcId)) {
            try {
                Map<String, String> params = new HashMap<>(2);
                params.put("pcId", pcId);
                params.put("tybm", tybm);
                // 发送请求
                String str = HttpAgent.getInstance().sendHttpPost(url2, params, null);
                if (StringUtils.isNotBlank(str)) {
                    JSONObject json = JSONObject.parseObject(str);
                    JSONObject jsonData = json.getJSONObject("data");
                    StringBuilder sbStr = new StringBuilder();
                    sbStr.append("<table>");
                    sbStr.append("<tr><td style='width:30%'>分数：</td><td style='width:70%'>" + isNull(jsonData.get("score")) + "</td></tr>");
                    sbStr.append("<tr><td>等级：</td><td>" + isNull(jsonData.get("rank")) + "</td></tr>");
                    if (!isBlank(jsonData.getString("cjsj"))) {
                        sbStr.append("<tr><td>评价日期：</td><td>" + DateUtils.dateParseString(DateUtils.getDate(Long.valueOf(jsonData.getString("cjsj")))) + "</td></tr>");
                    }
                    sbStr.append("</table>");
                    result.put("pjxxData", sbStr.toString());
                    result.put("pjxxDataStyle", "style=\"display: block;\"");
                } else {
                    result.put("pjxxData", "");
                    result.put("pjxxDataStyle", "style=\"display: none;\"");
                }
            } catch (Exception e) {
                RestServiceResult<List<Object>> userData = new RestServiceResult<>();
                userData.setCode(RestServiceResult.CODE_UNKNOW);
                userData.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error(
                        "远程服务-获取当前用户信息调用异常！(XypjRemoteBaseService#getReportDetail) URL:" + url + "Result:" + result,
                        e.getMessage(), e);
            }
        } else {
            result.put("pjxxData", "");
            result.put("pjxxDataStyle", "style=\"display: none;\"");
        }
        result.put("reportDate", DateUtils.getCurrentTime());
        return result;
    }

    private String isNull(Object o) {
        if (null != o)
            return String.valueOf(o);
        return "-";
    }

    private String formatDate(Object o) {
        if (null != o) {
            Date date = DateUtils.parseDateByFormat(String.valueOf(o), "yyyy-MM-dd");
            return DateUtils.dateParseShortString(date);
        }
        return "-";
    }

    private boolean isBlank(String str) {
        if (StringUtils.isBlank(str) || StringUtils.equals("undefined", str)) {
            return true;
        }
        return false;
    }
}
